package com.example.demo.controller;

import com.example.demo.convert.Convertor;
import com.example.demo.entity.SinaSHStockEntity;
import com.example.demo.entity.SinaUSStockEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/sina")
public class SinaController {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 上交所股票信息
     * @return
     */
    @RequestMapping("/SH")
    public List<SinaSHStockEntity> shInfo(){
        ResponseEntity<String> result = restTemplate.getForEntity("http://hq.sinajs.cn/list=sz002307,sh600928", String.class);
        String body = result.getBody();

        return convertSHStr2List(body);
    }

    /**
     * 美股信息
     * @return
     */
    @RequestMapping("/US/{stocks}")
    public List<SinaUSStockEntity> usInfo(@PathVariable String stocks){
        String url = "http://hq.sinajs.cn/list=" + stocks;
        //http://hq.sinajs.cn/list=gb_baba,gb_pdd,gb_aapl,gb_jd,gb_tsla,gb_ntes,gb_bidu
        ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
        String body = result.getBody();
        List<SinaUSStockEntity> list = convertUSStr2List(body);
        Collections.sort(list);
        return list;
    }

    /**
     * 将返回的字符串转换为json输出
     * @param str
     * @return
     */
    private List<SinaSHStockEntity> convertSHStr2List(String str){
        str = str.substring(0,str.lastIndexOf(";"));
        List<SinaSHStockEntity> list = new ArrayList<>();
        String[] strs = str.split(";");

        for (String s : strs) {
            s = s.substring(s.indexOf("\""), s.lastIndexOf("\""));
            list.add(Convertor.convertArr2SHEntity(s.split(",")));
        }
        return list;
    }

    /**
     * 将返回的字符串转换为json输出
     * @param str
     * @return
     */
    private List<SinaUSStockEntity> convertUSStr2List(String str){
        str = str.substring(0,str.lastIndexOf(";"));
        List<SinaUSStockEntity> list = new ArrayList<>();
        String[] strs = str.split(";");

        for (String s : strs) {
            s = s.substring(s.indexOf("\"")+1, s.lastIndexOf("\""));
            list.add(Convertor.convertArr2USEntity(s.split(",")));
        }
        return list;
    }
}
